<template>
    <div class='EditSet'>
        <list-box v-loading="loading" :list="listData" @onClick="clickKey" @onDelete="deleteKey">
            <el-button :loading="loading" @click="refresh" icon="el-icon-refresh-right" type="info" size="mini"></el-button>
            <el-button :disabled="loading" @click="drawerAddVisible = true" icon="el-icon-plus" type="success" size="mini">添加</el-button>
            <el-button style="margin-left:10px;" type="text" size="mini" disabled v-show="!loading">总数：{{total}}</el-button>
            <el-button class="ml-10" type="text" size="mini" disabled v-show="loading">{{timeout}}</el-button>
        </list-box>

        <edit-details v-model="isDetails" :select_item="select_item" @edit="editKey"
        v-model:page-size="page_size" :total="total" v-model:current-page="page" 
        @current-change="load_list" @size-change="refresh"/>

        <add-key-value @refresh="refresh" v-model="drawerAddVisible"></add-key-value>
    </div>
</template>

<script>
import { page_sizes } from '@/settings'
import { p_error } from '@/utils/prompt';
import { defineComponent, reactive, toRefs } from 'vue';
import { mapGetters } from 'vuex'
import { ElNotification, ElMessage } from 'element-plus'
import { set_srem, set_sscan } from '@/api/key/set';
import AddKeyValue from '../comps/AddKeyValue'
import ListBox from '../comps/ListBox'
import EditDetails from '../comps/EditDetails';
export default defineComponent({
    name: 'EditSet',
    components: { AddKeyValue, EditDetails, ListBox },
    setup(omprops, content) {
        const state = reactive({
            page_sizes,
            loading: true,
            drawerAddVisible: false, // 添加dialog是否显示 

            isDetails: false, // 详情是否打开
            select_item:undefined,

            timeout: 0, // 加载了时间


            match: "",//筛选
            total: 0,  //总数

            page: 1, //第几页
            page_size: 20,  // 每页的数量
            cursor: '0', // 当前游标
            listPage: [] //所有数据
        })
        return toRefs(state)
    },
    props: [], 
    computed: {
        ...mapGetters([
            'select_key',
            'key_type'
        ]),
        listData() {
            var sta = (this.page - 1) * this.page_size
            var end = this.page * this.page_size
            return this.listPage.slice(sta, end)
        }
    },
    watch: {
        // key变化
        select_key(n, o) {
                this.match = ''
                this.refresh()
        }
    },
    mounted() {
        this.refresh()
    },
    methods: {
        // 刷新
        refresh() {
             //主要判断没有正在加载(ing),切换key时，销毁不及时，会导致重复触发请求
            if (this.select_key == '' || this.key_type != 'set') {
                return
            }
            this.listPage = []
            this.page = 1
            this.total = 0
            this.cursor = "0"
            this.load_list()

            this.isDetails = false
        },
        // 加载数据
        load_list() {
            if (this.listPage.length > 0 && this.cursor == "0") return
            var zhong = this.page * this.page_size
            var size = zhong - this.listPage.length

            if (size < 1) return //无需加载

            if (this.listPage.length == 0) this.cursor = '0'
            this.loading = true;

            var time = 0
            this.timeout = `本次加载数量${size}条`
            const timeouter = setInterval(() => {
                time++
                this.timeout = `本次加载数量${size}条,已加载${time}秒`
            }, 1000);

            set_sscan({
                key: this.select_key, // key
                cursor: this.cursor,  // 游标
                match: "*" + this.match + "*", //模糊查询
                size,   //至少要加载多少条
                page_size: this.page_size //每次加载数量
            }).then((res) => {
                //添加到数组中
                for (let i = 0; i < res.data.list.length; i++) {
                    this.listPage.push(res.data.list[i])
                }
                this.total = res.data.map.total   //总数
                this.cursor = res.data.map.cursor //更新cursor
            }).finally(() => {
                clearInterval(timeouter)
                this.loading = false;
            })
        },
        // 点击key
        clickKey(item) {
            this.select_item = {
                value:item
            }
            this.isDetails = true
        },
        // 删除
        deleteKey(item) {
            p_error(`确定要删除 ${this.select_key} -> ${item} 吗？这将不可以恢复`, (instance, done) => {
                instance.confirmButtonLoading = true
                set_srem(this.select_key, item).then((res) => {
                    done()
                    ElNotification({
                        title: '删除成功',
                        message: `${item} 已被成功删除`,
                        type: 'success',
                    })
                    // 在列表中删除
                    this.listDelKey(item)
                }).finally(() => {
                    instance.confirmButtonLoading = false
                })
            })
        },
        editKey(data){
            this.select_item = data.new
            this.listEditKey(data.old, data.new)
        },

        // // 编辑提交
        // subEditKey() {
        //     if (this.edit.value == '') {
        //         this.deleteKey(this.edit.oldValue)
        //         ElMessage('你输入的内容为空,你想删除这个数据吗?')
        //         return
        //     }
        //     this.edit.loading = true
        //     set_sedit(this.select_key, this.edit.oldValue, this.edit.value).then((res) => {
        //         this.listEditKey(res.data.map.oldValue, res.data.map.value)
        //         this.edit.value = res.data.map.value
        //         this.edit.oldValue = res.data.map.value
        //         ElNotification({
        //             title: '修改成功',
        //             message: `${res.data.map.oldValue} -> ${res.data.map.value}`,
        //             type: 'success',
        //         })
        //     }).finally(() => {
        //         this.edit.loading = false
        //     })
        // },

        // 在列表中弃掉指定元素
        listDelKey(key) {
            var index = this.listPage.indexOf(key);
            if (index > -1) {
                this.listPage.splice(index, 1);
            }
            this.total--
        },
        listEditKey(oldKey, newKey) {
            var index = this.listPage.indexOf(oldKey);
            if (index > -1) {
                this.listPage[index] = newKey
            }
        },

        screen_editor() {
            ElMessage("开发中")
        }
    },
})
</script>

<style scoped lang="less">
// @import '@/assets/css/edit-list.less';
.EditSet {
    padding-top: 3px;
    flex: 1;
    width: 100%;
    height: 100%;
    // max-height: 100%;
    display: flex;
    flex-direction: column;
}
</style>